package com.qys.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import com.qys.handler.GetHttpHandler;
import com.qys.handler.PostHttpHandler;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

public class HttpUtils {
	
	private static Integer PORT = 80;
	
	public static void run() {
		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
			server.createContext("/testpost", new PostHttpHandler());
			server.createContext("/testget", new GetHttpHandler());
			server.setExecutor(Executors.newFixedThreadPool(10));
			server.start();
			System.out.println("-------------------- Http服务正在监听端口：" + PORT + " --------------------");
			System.out.println("1、可访问接口GET：/testget");
			System.out.println("2、可访问接口POST：/testpost");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理响应
	 * @throws Exception 
	 */
	public static void handleResponse(HttpExchange httpExchange, int code,String text) throws Exception {
		Headers headers = httpExchange.getResponseHeaders();
		headers.set("Content-Type", "text/html;charset=utf-8");
		byte[] responseContentByte = text.getBytes();
        httpExchange.sendResponseHeaders(code, responseContentByte.length);
        OutputStream out = httpExchange.getResponseBody();
        out.write(responseContentByte);
        out.flush();
        out.close();
	}
	
}
